﻿using MslDiary.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

// 版权所有：2014  All Rights Reserved.
// 文 件 名：DiaryBLL.cs
// 功能描述：
// 创建标识：m.sh.lin0328@163.com 2014/12/13 18:21:19
// 修改描述：F:\编程\个人项目\MslDiary\MslDiary.BLL\A_DiaryBLL.cs
//----------------------------------------------------------------*/
namespace MslDiary.BLL
{
    public class A_DiaryBLL : MSL.Tool.Data.DBAccessBase<Model.A_Diary>
    {
        A_AnnexBLL annexBLL = new A_AnnexBLL();
        #region 字段

        private const string DIARY_TABLE = @"
                        (
                           SELECT A.Id,A.IsDelete,A.Title,A.WeatherId,B.Name AS Weather,A.MoodId,C.Name AS Mood,A.TypeId,A.GroupId,E.Name AS GroupName,A.Summary,
                           A.DiaryDate,A.CreateDate,A.ModifyDate,A.DiaryYear,A.DiaryMonth,F.Num AS AttachNum 
                           FROM A_Diary A
                           LEFT JOIN A_Item B ON A.WeatherId=B.Id AND B.FatherId=12
                           LEFT JOIN A_Item C ON A.MoodId=C.Id AND C.FatherId=24
                           LEFT JOIN A_Item E ON A.GroupId=E.Id AND E.FatherId=22 
                           LEFT JOIN (
                                SELECT FromRecordId,COUNT(1) AS Num FROM A_Annex WHERE FromTable='A_Diary' AND FromField='' GROUP BY FromRecordId
                           ) AS F ON F.FromRecordId=A.Id
                        )AS A
                         ";
        #endregion
        #region 构造

        public A_DiaryBLL()
            : base("A_Diary", "Id", true)
        {

        }
        #endregion

        public int Add(A_Diary model, ArrayList alImage)
        {
            SaveImages(ref model, alImage);
            if (base.Add(model) > 0)
            {
                try
                {
                    //更新 FromRecordId
                    int id = GetMaxId();
                    MSL.Tool.Data.DbHelper.Instance.ExecSql("UPDATE A_Annex SET FromRecordId=" + id + " WHERE FromRecordId=0 ", new Hashtable());
                    //更新没有添加上日记Id的图片标识
                    model.Content = model.Content.Replace("[$IMG-0-", String.Format("[$IMG-{0}-", id));
                    //model.Content = MSL.Tool.Security.DESEncrypt.Instance.Encrypt(model.Content, Framework.Gloable.DiaryEncryptKey);//加密
                    base.Update(model, " Id=" + id);
                    //拷贝临时文件
                    string orginalPath = MslDiary.Framework.Gloable.CachePath + "0\\";
                    string copyPath = MslDiary.Framework.Gloable.CachePath + id + "\\";
                    MSL.Tool.IOHelper.Instance.CopyFolder(orginalPath, copyPath);

                    //如果是图片压缩
                    //foreach (string path in MSL.Tool.IOHelper.Instance.GetAllFiles(copyPath, new string[] { ".jpeg", ".jpg", ".png", ".bmp" }))
                    //{
                    //    MslDiary.Framework.ImageHelper.ChangeImage();
                    //}
                    //MslDiary.Framework.ImageHelper.ChangeImage();
                    MSL.Tool.IOHelper.Instance.DeleteFolder(MslDiary.Framework.Gloable.CachePath + "0\\");
                    return 1;
                }
                catch (Exception ex)
                {
                    MslDiary.Framework.IO.LogHelper.SaveLog("BLL A_DiaryBLL Add id[" + model.Id + "]", ex.ToString());
                    return 0;
                }

            }
            //删除 FromRecordId=0
            return 0;
        }
        public int Update(A_Diary model, string where, ArrayList alImage)
        {
            SaveImages(ref model, alImage);
            //日记内容不加密
            //model.Summary = MSL.Tool.Security.DESEncrypt.Instance.Encrypt(model.Summary, Framework.Gloable.DiaryEncryptKey);//加密
            //model.Content = MSL.Tool.Security.DESEncrypt.Instance.Encrypt(model.Content, Framework.Gloable.DiaryEncryptKey);//加密
            if (base.Update(model, where) > 0)
            {
                //更新 FromRecordId
                MSL.Tool.Data.DbHelper.Instance.ExecSql("UPDATE A_Annex SET FromRecordId=" + model.Id + " WHERE FromRecordId=0 ", new Hashtable());
                return 1;
            }
            //删除 FromRecordId=0
            return 0;
        }
        public string LoadImages(string diaryXaml)
        {
            string result = diaryXaml;
            if (String.IsNullOrEmpty(result)) return String.Empty;

            string reg = @"\[\$IMG\-(\d+)\-(\d+)\-(\d+)-(.*?)-(.*?)\$\]"; //图片占位符:$1、$2、$3、$4 、$5 分别代表图片id、宽度、高度、文件夹、文件类型
            Regex re = new Regex(reg, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            MatchCollection mcs = re.Matches(result);
            string id, width, height, src, type, recordId, tmp;
            MSL.Tool.IOHelper.Instance.CreateFolder(MslDiary.Framework.Gloable.CachePath);
            foreach (Match mc in mcs)
            {
                id = mc.Groups["1"].Value;
                width = mc.Groups["2"].Value;
                height = mc.Groups["3"].Value;
                recordId = mc.Groups["4"].Value;
                type = mc.Groups["5"].Value;
                src = MslDiary.Framework.Gloable.CachePath + recordId + "\\" + id + "." + type;

                tmp = String.Format("file:///{0}", src.Replace(@"\", "/"));
                reg = String.Format(@"\[\$IMG\-{0}\-(\d+)\-(\d+)-(.*?)-(.*?)\$\]", id);
                result = Regex.Replace(result, reg, tmp, RegexOptions.IgnoreCase);
            }
            return result;
        }
        private void SaveImages(ref A_Diary model, ArrayList alImage)
        {
            //删除所有 重新添加 --不太好
            MSL.Tool.IOHelper.Instance.CreateFolder(MslDiary.Framework.Gloable.CachePath + "0\\");//日记没有添加成功时的图片临时目录
            string path = "";
            string name = "";
            try
            {
                MSL.Tool.Data.DbHelper.Instance.ExecSql("DELETE FROM A_Annex WHERE FromTable='A_Diary' AND fromField='Content' AND fromrecordid=" + model.Id + " ", new Hashtable());
                if (alImage != null && alImage.Count > 0)
                {
                    string src, w, h;
                    A_Annex mod;
                    foreach (string[] arr in alImage)
                    {
                        src = arr[1];
                        if (!File.Exists(src)) continue;
                        w = arr[2];
                        h = arr[3];

                        FileInfo fi = new FileInfo(src);
                        mod = new A_Annex();
                        mod.Name = fi.Name;
                        mod.Suffix = "." + fi.Name.Split('.')[1];
                        mod.FileType = MslDiary.Framework.Helper.GetFileType(mod.Suffix);
                        mod.FileSize = fi.Length / 1024;
                        mod.FromTable = "A_Diary";
                        mod.FromField = "Content";
                        mod.FromRecordId = 0;
                        mod.CreateDate = DateTime.Now;
                        mod.Content = MslDiary.Framework.Helper.FileToByte(src);
                        annexBLL.Add(mod);

                        int id = 0;
                        object obj = MSL.Tool.Data.DbHelper.Instance.ExecScalar("SELECT MAX(ID) FROM A_Annex", new Hashtable());
                        if (obj != null) id = Int32.Parse(obj.ToString());

                        name = src.Substring(src.LastIndexOf('/') + 1).Split('.')[0];
                        path = MslDiary.Framework.Gloable.CachePath + model.Id;
                        MSL.Tool.IOHelper.Instance.CreateFolder(path);
                        path = path + "\\" + id + (mod.Suffix.StartsWith(".") ? mod.Suffix : "." + mod.Suffix);
                        if (!src.Contains(@"\cache\"))
                            fi.CopyTo(path, true);

                        model.Content = model.Content.Replace("file:///" + src, String.Format("[$IMG-{0}-{1}-{2}-{3}-{4}$]", id, w, h, model.Id, mod.Suffix.Replace(".", "")));
                    }
                }

            }
            catch (Exception ex)
            {
                MslDiary.Framework.IO.LogHelper.SaveLog("BLL A_DiaryBLL SaveImages id[" + model.Id + "]", ex.ToString());
            }
        }
        public int RecycleDiaryCount()
        {
            object obj = MSL.Tool.Data.DbHelper.Instance.ExecScalar(" SELECT COUNT(1) FROM A_Diary WHERE IsDelete='1' ", new Hashtable());
            return obj == null ? 0 : Convert.ToInt32(obj.ToString());
        }
        public int GetMaxId()
        {
            object obj = MSL.Tool.Data.DbHelper.Instance.ExecScalar(" SELECT MAX(Id) FROM A_Diary ", new Hashtable());
            return obj == null ? 0 : Convert.ToInt32(obj.ToString());
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dateFieldName">日期字段</param>
        /// <param name="type">查询类别</param>
        /// <param name="whereSql">条件</param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="sortBy"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public List<Model.A_Diary> GetPageList(string dateFieldName, Model.SearchType type, string whereSql, int pageSize, int pageIndex, string sortBy, out int recordCount, out string searchWhere)
        {
            List<Model.A_Diary> list = new List<Model.A_Diary>();

            #region 条件

            string where = " 1=1 ";
            if (!String.IsNullOrEmpty(whereSql))
                where += whereSql;
            if (String.IsNullOrEmpty(dateFieldName))
                dateFieldName = "DiaryDate";
            if (String.IsNullOrEmpty(sortBy))
                sortBy = "DiaryDate DESC";
            switch (type)
            {
                case Model.SearchType.All:
                    break;
                case Model.SearchType.Year://今年
                    where += String.Format(" AND {0}>=date('" + DateTime.Now.Year + "-01-01')", dateFieldName);
                    break;
                case Model.SearchType.Month://当月
                    where += String.Format(" AND {0}>=date('" + DateTime.Now.ToString("yyyy-MM-01") + "')", dateFieldName);
                    break;
                case Model.SearchType.Day://当天
                    where += String.Format(" AND date({0})=date('" + DateTime.Now.ToString("yyyy-MM-dd") + "')", dateFieldName);
                    break;
                case Model.SearchType.Lately7Days://最近7天
                    where += String.Format(" AND {0}>=date('" + DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd") + "')", dateFieldName);
                    break;
                case Model.SearchType.Lately30Days://最近30天
                    where += String.Format(" AND {0}>=date('" + DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd") + "')", dateFieldName);
                    break;
                default:
                    break;
            }
            #endregion
            searchWhere = where;
            return base.GetList(null, DIARY_TABLE, pageSize, pageIndex, "*", where, sortBy, out recordCount);
        }

        /// <summary>
        /// 从回收站恢复
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool RecoveryDiaryById(int id)
        {
            int result = MSL.Tool.Data.DbHelper.Instance.ExecSql(" UPDATE A_Diary SET IsDelete='0' WHERE IsDelete='1' AND Id=" + id, new Hashtable());
            return result > 0;
        }
        /// <summary>
        /// 根据历史条件查询
        /// </summary>
        /// <param name="historyWhere"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="sortBy"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public List<Model.A_Diary> GetPageListByHistoryWhere(string historyWhere, int pageSize, int pageIndex, string sortBy, out int recordCount)
        {
            recordCount = 0;
            if (String.IsNullOrEmpty(historyWhere))
                return null;
            if (String.IsNullOrEmpty(sortBy))
                sortBy = "DiaryDate DESC";

            return base.GetList(null, DIARY_TABLE, pageSize, pageIndex, "*", historyWhere, sortBy, out recordCount);
        }
        /// <summary>
        /// 解密所有日记内容文本 临时使用 --> 已废除
        /// </summary>
        public void DESEncryptContent()
        {
            List<Model.A_Diary> list = new List<Model.A_Diary>();
            list = base.GetList(" 1=1 ", "*", " ID");
            foreach (Model.A_Diary mod in list)
            {
                if (mod != null && mod.Content != null && !mod.Content.Contains("<"))
                {
                    mod.Summary = MSL.Tool.Security.DESEncrypt.Instance.Decrypt(mod.Summary, Framework.Gloable.DiaryEncryptKey);//解密
                    mod.Content = MSL.Tool.Security.DESEncrypt.Instance.Decrypt(mod.Content, Framework.Gloable.DiaryEncryptKey);//解密
                }
                base.Update(mod, " Id=" + mod.Id);
            }
        }
        /// <summary>
        /// 根据日期修改默认标题
        /// </summary>
        public void UpdateTitleByDate(ref A_Diary mod)
        {
            //修改默认标题
            if (mod != null && mod.Title != null)
                mod.Title = MslDiary.Framework.Text.CText.Replace(
                    mod.Title,
                    @"(19|20)\d\d-\d{2}-\d{2}\s*周[一二三四五六日]",
                    mod.DiaryDate.ToString("yyyy-MM-dd") + " " + MslDiary.Framework.CanlendarHelper.WeekDayStr(mod.DiaryDate).Replace("星期", "周")
                    );
        }
        public A_Diary GetModelById(int id)
        {
            if (id == 0)
                return null;
            A_Diary mod = base.GetEntity(" Id = " + id);
            //if (mod != null && mod.Content != null && !mod.Content.StartsWith("<FlowDocument"))
            //{
            //    mod.Content = MSL.Tool.Security.DESEncrypt.Instance.Decrypt(mod.Content, Framework.Gloable.DiaryEncryptKey);//解密 

            //}
            this.annexBLL.DeleteTmpContentImage();//清空没有保存的图片
            LoadImages(mod.Content);
            annexBLL.ReadFileAddCachedByRecordId(mod.Id);
            return mod;
        }
        /// <summary>
        /// 清空回收站 删除文件
        /// </summary>
        /// <returns></returns>
        public int ClearRecycle()
        {
            //删除文件表数据
            annexBLL.Delete(
                String.Format(" FromTable='{0}' AND FromField={1} AND FromRecordId IN( SELECT Id FROM A_Diary WHERE {2} ) ",
                              "A_Diary",
                              "Content",
                              "IsDelete='1' "
                )
            );
            //删除日记
            return base.Delete(" IsDelete='1' ");
        }
        /// <summary>
        /// 恢复全部回收站数据
        /// </summary>
        /// <returns></returns>
        public int RecoveryRecycle()
        {
            return MSL.Tool.Data.DbHelper.Instance.ExecSql(" UPDATE A_Diary SET IsDelete='0' WHERE IsDelete='1' ", new Hashtable());
        }
        public A_Diary GetModelByDiaryDate(DateTime diaryDate)
        {
            A_Diary mod = base.GetEntity(" date(DiaryDate) = date('" + diaryDate.ToString("yyyy-MM-dd") + "') ");
            //if (mod != null && mod.Content != null && !mod.Content.Contains("<"))
            //{
            //    mod.Content = MSL.Tool.Security.DESEncrypt.Instance.Decrypt(mod.Content, Framework.Gloable.DiaryEncryptKey);//解密
            //    annexBLL.ReadFileAddCachedByRecordId(mod.Id);
            //}
            if (mod != null)
                this.annexBLL.ReadFileAddCachedByRecordId(mod.Id);
            this.annexBLL.DeleteTmpContentImage();
            return mod;
        }
        /// <summary>
        /// 根据日期统计 2014:12|2014:11|2014:10
        /// </summary>
        /// <returns></returns>
        public string GetCensusByDate()
        {
            StringBuilder sb = new StringBuilder();
            string sql =
@"
SELECT DiaryYear,DiaryMonth,COUNT(1) AS Num FROM A_Diary 
WHERE IsDelete=0 AND IsEnable=1 
GROUP BY DiaryYear,DiaryMonth ORDER BY DiaryYear DESC,DiaryMonth DESC 
";
            using (DataTable dt = MSL.Tool.Data.DbHelper.Instance.Query(sql, new Hashtable()))
            {
                if (dt == null || dt.Rows.Count == 0)
                    return String.Empty;
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr["DiaryYear"].ToString().Length == 0)
                        continue;

                    sb.Append(dr["DiaryYear"].ToString());
                    sb.Append("-");
                    sb.Append(dr["DiaryMonth"].ToString());
                    sb.Append("-");
                    sb.Append(dr["Num"].ToString());
                    sb.Append("|");
                    //result += dr["DiaryMonth"].ToString() + ":" + dr["DiaryMonth"].ToString() + "|";
                }
                if (sb.Length > 0)
                    sb = sb.Remove(sb.Length - 1, 1);
            }
            return sb.ToString();
        }

        public bool IsExists(DateTime diaryDate)
        {
            if (diaryDate.Year == 1990) return false;
            return base.Count(" date(DiaryDate) = date('" + diaryDate.ToString("yyyy-MM-dd") + "') AND IsDelete=0") > 0 ? true : false;
        }
    }
}
